package com.game.network.http;

import com.alibaba.fastjson.JSONObject;
import com.game.common.error.GameErrorException;
import com.game.common.error.IServerError;
import com.game.network.error.GameCenterError;
import com.game.network.http.response.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * http全局异常捕获
 */
@ControllerAdvice
public class GlobalExceptionCatch {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionCatch.class);

    @ResponseBody
    @ExceptionHandler(value = Throwable.class)
    public ResponseEntity<JSONObject> exceptionHandler(Throwable e) {
        IServerError error = null;
        if(e instanceof GameErrorException gameErrorException) {
            error = gameErrorException.getError();
            logger.error("服务器异常，{}", e.getMessage());
        } else {
            error = GameCenterError.UNKNOWN;
            logger.error("服务器异常，{}", e.getMessage());
        }
        JSONObject data = new JSONObject();
        data.put("errorMsg", e.getMessage());
        ResponseEntity<JSONObject> response = new ResponseEntity<>(error);
        response.setData(data);
        return response;
    }
}
